<template>
  <div class="user">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索框 -->
    <div style="margin-top: 15px;">
      <el-input placeholder="请输入搜索关键字" v-model="query" class="input-with-select">
        <el-button @click='search' slot="append" icon="el-icon-search"></el-button>
      </el-input>
      <el-button type='success' plain  class='btnAdd'  @click='showAddDialog'>添加用户</el-button>
    </div>
    <!-- 表格 -->
    <el-table :data='userList'>
      <el-table-column label='姓名' prop='username'></el-table-column>
      <el-table-column label='邮箱' prop='email'></el-table-column>
      <el-table-column label='电话' prop='mobile'></el-table-column>
      <el-table-column label='用户状态' >
        <template v-slot='obj'>
          <el-switch
            @change='changeState(obj.row.id,obj.row.mg_state)'
            v-model="obj.row.mg_state"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label='操作'>
      <template v-slot='{ row }'>
        <el-button plain size='small' type='primary' @click="showEditDialog(row)" icon='el-icon-edit'></el-button>
        <el-button plain @click='delUser(row.id)' size='small'  type='danger' icon='el-icon-delete'></el-button>
        <el-button plain size='small' @click='showAssignDialog(row)'  type='success' icon='el-icon-check'>分配角色</el-button>
      </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagenum"
      background
      :page-sizes="[2,4,6,8,10]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

    <!-- 添加的对话框 -->
    <el-dialog
      @close='closeAddDialog'
      title="添加用户"
      :visible.sync="dialogVisible"
      width="40%">
       <el-form  ref="form" :model="form" :rules="rules"  label-width="80px">
        <el-form-item label="用户名"  prop='username'>
          <el-input placeholder="请输入用户名"  v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码"  prop='password'>
          <el-input  type='password' placeholder="请输入密码"  v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱"  prop='email'>
          <el-input  placeholder="请输入邮箱"  v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="手机"  prop='mobile'>
          <el-input  placeholder="请输入手机号码"  v-model="form.mobile"></el-input>
        </el-form-item>
       </el-form>
       <template v-slot:footer>
          <span  class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
          </span>
       </template>
    </el-dialog>

    <!-- 修改的对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editVisible"
      width="40%">
       <el-form  ref="editForm" :model="editForm" :rules="rules"  label-width="80px">
        <el-form-item label="用户名" >
          <el-tag type='info'>{{ editForm.username }}</el-tag>
        </el-form-item>
        <el-form-item label="邮箱"  prop='email'>
          <el-input  type='password' placeholder="请输入邮箱"  v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机"  prop='mobile'>
          <el-input  placeholder="请输入手机号码"  v-model="editForm.mobile"></el-input>
        </el-form-item>
       </el-form>
       <!-- 具名插槽 template标签包裹, 指定 v-slot:插槽名 -->
       <template v-slot:footer>
          <span  class="dialog-footer">
            <el-button @click="editVisible = false">取 消</el-button>
            <el-button type="primary" @click="editUser">确 定</el-button>
          </span>
       </template>
    </el-dialog>

    <!-- 分配的对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="assignVisible"
      width="40%">
       <el-form  ref="assignForm" :model="assignForm" label-width="80px">
        <el-form-item label="用户名" >
          <el-tag type='info'>{{ assignForm.username }}</el-tag>
        </el-form-item>
        <el-form-item label="角色列表">
           <!-- select框的value值, 就是选中的option的value值 -->
         <el-select v-model="assignForm.rid"  placeholder="请选择">
            <el-option v-for='item in options' :key='item.id' :label='item.roleName'   :value="item.id"></el-option>
          </el-select>
         </el-form-item>
       </el-form>
       <!-- 具名插槽 template标签包裹, 指定 v-slot:插槽名 -->
       <template v-slot:footer>
          <span  class="dialog-footer">
            <el-button @click="assignVisible = false">取 消</el-button>
            <el-button type="primary" @click="assignRole">确 定</el-button>
          </span>
       </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  // 组件配置怎么写, 这里就怎么写, data, methods, computed
  data () {
    return {
      query: '',
      pagenum: 1,
      pagesize: 2,
      userList: [],
      total: 0,
      dialogVisible: false,
      form: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: ['blur', 'change'] },
          { min: 3, max: 12, message: '长度在3-12位', trigger: ['blur', 'change'] }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: ['blur', 'change'] },
          { min: 3, max: 12, message: '长度在3-12位', trigger: ['blur', 'change'] }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱', trigger: ['blur', 'change'] }
        ],
        mobile: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: ['blur', 'change'] }
        ]
      },
      editVisible: false,
      editForm: {
        id: '', // 修改  需要获取id
        username: '',
        email: '',
        mobile: ''
      },
      assignVisible: false,
      assignForm: {
        username: '', // 回显的用户名
        id: '', // 用户id, 正在分配角色给哪一个用户
        rid: ''// 角色id, 分配的角色的id
      },
      options: [] // 可供选择的角色列表
    }
  },
  created () {
  // ajax在created里面发
    this.getList()
  },
  methods: {
    async getList () {
      // 注意get/post 发送格式不同
      const { meta, data } = await this.$axios.get('users', {
        params: { // 会拼接到地址栏里
          query: this.query,
          pagenum: this.pagenum,
          pagesize: this.pagesize
        }
      })
      if (meta.status === 200) {
        // 成功, 应该将 users / total 存起来, 用于表格的渲染
        this.userList = data.users
        this.total = data.total
      } else {
        this.$message.console.error(meta.msg)
      }
    },
    // 用async,await,promise优化代码
    async changeState (id, flag) {
      // 去看接口文档
      // - 请求路径：users/:uId/state/:type
      // - 请求方法：put
      const { meta } = await this.$axios.put(`users/${id}/state/${flag}`)
      if (meta.status === 200) {
        this.$message.success(meta.msg)
      } else {
        this.$message.error(meta.msg)
      }
    },
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.pagesize = val
      this.pagenum = 1
      this.getList()
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.pagenum = val
      this.getList()
    },
    search () {
      // query 不需提交 数据双向绑定了
      // 渲染函数里面就是更新了的query
      // 从第一页  重新渲染
      this.pagenum = 1
      this.getList()
    },
    async delUser (id) {
      try {
        await this.$confirm('亲, 你确认要进行删除操作么?', '温馨提示', {
          type: 'warning'
        })
        // 确认了 发送ajax
        const { meta } = await this.$axios.delete(`users/${id}`)
        if (meta.status === 200) {
          this.$message.success(meta.msg)
          // 如果删除的是当前页仅有的一条数据, 那么当前页要 --
          if (this.userList.length === 1 && this.pagenum > 1) { this.pagenum-- }
          this.getList()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (e) {
        console.log('取消了')
      }
    },
    showAddDialog () {
      this.dialogVisible = true
    },
    async addUser () {
      try {
        // 1. 先进行表单校验
      // 2. 发送添加的 ajax 请求
        await this.$refs.form.validate()
        // 校验成功  发送ajax
        const { meta } = await this.$axios.post('users', this.form)
        if (meta.status === 201) {
          this.$message.success(meta.msg)
          // 关闭对话框
          this.dialogVisible = false
          // 重新渲染, 渲染最后一页
          // this.pagenum = 最后一页
          // 总共15条, 每页5条, 3页, 小细节: 这里 this.total 还是之前未添加之前的total
          // 需要让 this.total 先 + 1 再运算
          this.total++
          this.pagenum = Math.ceil(this.total / this.pagesize)
          this.getList()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (e) {
        console.log(e)
      }
    },
    closeAddDialog () {
      // 可以统一进行清空表单的数据
      // 只要关闭了对话框, 都会触发这个函数
      this.$refs.form.resetFields()
    },
    showEditDialog (row) {
      this.editVisible = true
      // 数据回显
      // 数据修改了, 绑定的视图, 自动更新
      this.editForm.id = row.id
      this.editForm.username = row.username
      this.editForm.email = row.email
      this.editForm.mobile = row.mobile
    },
    async   editUser () {
      try {
        await this.$refs.editForm.validate()
        // 只要能够到这里, 说明校验成功了
        const { id, email, mobile } = this.editForm
        const { meta } = await this.$axios.put(`users/${id}`, { email, mobile })
        if (meta.status === 200) {
          this.$message.success(meta.msg)
          // 关闭对话框
          this.editVisible = false
          this.getList() // 重新渲染
        } else {
          this.$message.error(meta.msg)
        }
      } catch (e) {
        console.log(e)
      }
    },
    async showAssignDialog (row) {
      this.assignVisible = true
      // 回显用户名, 存储用户 id
      this.assignForm.username = row.username
      this.assignForm.id = row.id
      // 角色 id 也要回显  怎么办
      // this.assignForm.rid = row.rid
      const resUser = await this.$axios.get(`users/${row.id}`)
      if (resUser.meta.status === 200) {
        // 这里的 rid, 如果是新添加的用户, 值是 -1, 应该值是 '', 显示给用户成请选择
        const rid = resUser.data.rid
        this.assignForm.rid = rid === -1 ? '' : rid
      }
      // 一显示对话框, 就发送ajax请求, 获取角色列表, 用于下拉菜单的展示
      const { data, meta } = await this.$axios.get('roles')
      if (meta.status === 200) {
        this.options = data
        console.log(this.options)
      } else {
        this.$message.error(meta.msg)
      }
    },
    async  assignRole () {
      const { id, rid } = this.assignForm
      if (rid === '') return
      // 发送分配的 ajax 请求即可
      const { meta } = await this.$axios.put(`users/${id}/role`, { rid })
      if (meta.status === 200) {
        this.$message.success(meta.msg)
        // 关闭模态框
        this.assignVisible = false
        this.getList()
      } else {
        this.$message.error(meta.msg)
      }
    }
  }
}
</script>

<style lang='scss' scoped>
.input-with-select {
  width: 300px;
  margin-bottom: 10px;
}
.btnAdd {
  margin-left: 10px;
}
</style>
